<template>
    <div class="data-scope-modal" v-if="state.open" ref="dataScopeModalRef">
        <a-modal 
            width="500px"
            wrapClassName="custom-modal"
            v-model:open="state.open" 
            title="数据范围" 
            cancelText="取消"
            okText="确定"
            @ok="handleOk"
            @cancel="handleCancel"
            :getContainer="() => $refs.dataScopeModalRef"
        >
            <a-form
                :model="state.formState"
                name="dataScopeForm"
                autocomplete="off"
                class="w-full"
                layout="vertical"
            >
                <a-form-item label="数据范围">
                    <a-select class="w-full" v-model:value="state.formState.dataScope">
                        <a-select-option v-for="item in useMapDictList('DataScopeEnum')" :key="item.value" :value="+item.value">
                            {{ item.label }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="机构列表" v-show="state.formState.dataScope == 5">
                    <org-tree ref="orgTreeRef" :tenant-id="state.formState.tenantId" :checkable="true"/>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { ItemType } from '../type';
import { useMapDictList } from '@/hooks';
import orgTree from '../../org/components/orgTree.vue';
import { apiSysRoleGrantDataScopePost, apiSysRoleOwnOrgListGet } from '@/api/sys/sysRole';
import type { ResType } from '@/api/types';
import { showMsg } from '@/utils';
const emits = defineEmits<{
    (e:"handleQuery"):void
}>()
const dataScopeModalRef=ref()
const orgTreeRef = ref<InstanceType<typeof orgTree>>()
const state = reactive({
    open:false,
    formState:{} as ItemType,
})

const handleOk = async() => {
    if(state.formState.dataScope == 5){
        state.formState.orgIdList= orgTreeRef.value?.getCheckedKeys()
    }
    await apiSysRoleGrantDataScopePost(state.formState)
    showMsg("操作成功",'success')
    handleCancel()
    emits("handleQuery")
}


const handleCancel = () => {
    state.open = false; 
}

const handleOpen =async (row:ItemType) => {
    state.open = true;
    state.formState = JSON.parse(JSON.stringify(row))
    // 获取自定义组织数据
    if(state.formState.dataScope == 5){
        if(!row.id) return
        const res = await apiSysRoleOwnOrgListGet(row.id) as ResType<number[]>
        setTimeout(() => {
            // 因为同时打开渲染组件数据可能没有加载完成
            orgTreeRef.value?.setCheckedKeys(res.data.result)
        }, 100);
    }
}

defineExpose({
    handleOpen
})
</script>

<style lang="scss" scoped>
    
</style>